package com.lw.leetcode.str.a;

/**
 * Created with IntelliJ IDEA.
 * 2047. 句子中的有效单词数
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/27 9:47
 */
public class CountValidWords {
    public int countValidWords(String sentence) {
        int n = sentence.length();
        int ans = 0;
        for (int i = 0; i < n; ) {
            while (i < n && sentence.charAt(i) == ' ') {
                i++;
            }
            if (i >= n) {
                break;
            }
            int j = i;
            while (j < n && sentence.charAt(j) != ' ') {
                j++;
            }
            String w = sentence.substring(i, j);
            if (find(w)) {
                ans++;
            }
            i = j;
        }
        return ans;
    }
    private boolean find(String s) {
        boolean hasHyphen = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                return false;
            } else if (c == '-') {
                if (hasHyphen || i == 0 || i == s.length() - 1) {
                    return false;
                }
                if (s.charAt(i - 1) < 'a' || s.charAt(i - 1) > 'z' || s.charAt(i + 1) < 'a' || s.charAt(i + 1) > 'z') {
                    return false;
                }
                hasHyphen = true;
            } else if (c == '!' || c == '.' || c == ',') {
                if (i != s.length() - 1) {
                    return false;
                }
            }
        }
        return true;
    }
}
